package com.tygz.interceptor;

import java.io.IOException;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.auto.base.pojo.SysUser;
import com.auto.common.SessionInfo;
import com.auto.util.SystemUtil;
import com.base.common.CommonConstants;
import com.base.util.JUtil;


public class CheckLoginFilter implements Filter {

	private static final String[] IGNORE_URI = {"jspmanagelogin.jsp","jspothererror.jsp","image.html"};
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		    HttpServletRequest request = (HttpServletRequest) servletRequest;
	        HttpServletResponse response = (HttpServletResponse) servletResponse;
	        HttpSession session = request.getSession();
	       
	        
	        
	        // 获得用户请求的URI
	        String requestPath =JUtil.getRequestPath(request);
	        String contextPath = request.getContextPath();
	        
	        for(String url:IGNORE_URI){
	        	if(url.equals(requestPath)){
	        		chain.doFilter(request, response);
	        		return;
	        	}
	        }
	        
	        SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(CommonConstants.SESSION_MANAGE_USER);
			if (sessionInfo == null) {// 没有登录系统，或登录超时
				System.out.println("用户未登陆！");
				response.sendRedirect(contextPath+"/jsp/manage/login.jsp");
				return;
			}
			
	        boolean flag1 =SystemUtil.getInstance().isContainsUrl(requestPath),flag2=SystemUtil.getInstance().isContainExtraPath(requestPath);
	        if(!flag1 && !flag2){
	        	chain.doFilter(request, response);
				return ;
	        }
	        
	      
	        
			SysUser user = sessionInfo.getSysUser();
			if (user.getUserType() == 0) {// 超级管理员不需要验证权限
				chain.doFilter(request, response);
				return ;
			}
			
			Set<String> allowUrls = sessionInfo.getAllowUrl();
			if (allowUrls.contains( requestPath) || SystemUtil.getInstance().isContainExtraPath(requestPath)) {// 验证当前用户是否有权限访问此资源
				chain.doFilter(request, response);
			} else {
				System.out.println("无权访问该资源！");
				response.sendRedirect(contextPath+"/jsp/other/error.jsp");
			}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
